package com.itheima.demo06;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/7/15 9:18
 */
public class MyRunnable01 implements Runnable {
    private String pathName;
    private CountDownLatch cdl;
    private ConcurrentHashMap<String, String> map;

    public MyRunnable01(String pathName, CountDownLatch cdl, ConcurrentHashMap<String, String> map) {
        this.pathName = pathName;
        this.cdl = cdl;
        this.map = map;
    }

    @Override
    public void run() {
        //创建字符输入流和字符输出流;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //读取文件;
            bis = new BufferedInputStream(new FileInputStream(pathName));
            //因为没次需要copy一个文件,所以输出流的名字没次就需要一一对应;
            File file = new File(pathName);
            String name = file.getName();
            bos = new BufferedOutputStream(new FileOutputStream("E:\\copy\\" + name));
            //开始读写数据,一次读写一个数组的内容;
            byte[] arr = new byte[1024 * 8];
            int len;
            while ((len = bis.read(arr)) != -1) {
                bos.write(arr, 0, len);
                bos.flush();
            }
            //将文件名和完成时间添加到map集合当中 ;
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String endTime = sdf.format(date);
            //向集合中添加元素;
            map.put(pathName, endTime);
            //告诉主线程我执行完成了;
            cdl.countDown();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关流;
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
